package com.actionsky.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.actionsky.dao.SearchDAO;
import com.actionsky.entity.SearchMatch;
import com.actionsky.entity.SearchResult;
import com.actionsky.entity.SubPages;

public class SearchAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private List<SearchResult> list = null;
		
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		// The "q" is a word in search form.
		String q = request.getParameter("q")==null?request.getSession().getAttribute("q").toString():request.getParameter("q").trim();
		request.getSession().setAttribute("q", q);
		int group = Integer.parseInt(request.getParameter("group"));	//过滤条件
		//页数
		int page_number = Integer.parseInt(request.getParameter("start"));
		int start =(page_number-1)*10;		//start 从第几条记录开始
		SearchMatch sm = null;	//匹配状态(总记录数)
		int rowcount = 0;
		int end = Integer.parseInt(request.getParameter("end"));	//搜索页每页显示条数，default is 10.
		//判断关键字是否为空字符串
		if(q.length() == 0){
			request.getSession().removeAttribute("q");
			list = null;	
		}else{
			list = SearchDAO.searchFullText(q, group, start, end);
			sm = SearchDAO.matchsTotle(q);
			if(sm.getMatches() == 0) rowcount=1;
			else rowcount = sm.getMatches();
			/*
			PageSet pageset=new PageSet();
			pageset.setRowcount(rowcount);
			pageset.setCurrentpage(page_number);
			pageset.setPagecount((rowcount+10-1)/10);
			pageset.setPagesize(10);
			request.getSession().setAttribute("pageset", pageset);
			*/
			/** 参数：1=>每页显示记录数,2=>总记录数,3=>当前页,4=>每次显示页数,5=>分页url **/
			SubPages pages = new SubPages(end, rowcount, page_number, 10,"http://www.actionsky.com");
			String results_page = pages.subPageCss2();
			
			request.getSession().setAttribute("results_page", results_page);
			request.getSession().setAttribute("search_match", sm);
		}
		
		request.getSession().setAttribute("group", group);
		request.getSession().setAttribute("search_result", list);
		response.sendRedirect("index.jsp");
	}

	public void init() throws ServletException {
	}
	public void destroy() {
		super.destroy(); 
	}
}
